﻿using System.IO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Marbles.Core.Content.Sites;
using Marbles.Core.Content.Pages;
using Marbles.Core.Settings;

namespace Marbles.Core.Handlers
{
    public class ContentHandler : HttpHandlerBase, IHttpHandlerBase
    {
        public string Verbs
        {
            get { return "*"; }
        }

        public bool Validate
        {
            get { return false; }
        }

        public string Path
        {
            get { return "CMS.axd"; }
        }

        public string Name
        {
            get { return this.GetType().Name; }
        }

        public bool IsReusable
        {
            get { return false; }
        }

        public void ProcessRequest(System.Web.HttpContext context)
        {
            string op = "";
            string id = string.Empty;
            string response = string.Empty;

            string pagename = System.IO.Path.GetFileNameWithoutExtension(context.Request.UrlReferrer.AbsolutePath);
            SiteDefinition Web = SiteDefinition.GetCurrent();

            if (SettingsManager.TrustLevel == System.Web.AspNetHostingPermissionLevel.Medium)
            {
                System.Collections.Specialized.NameValueCollection parameters = System.Web.HttpUtility.ParseQueryString(context.Request.UrlReferrer.Query);
                if (parameters["id"] != null)
                {
                    pagename = parameters["id"];
                }
            }

            if (string.IsNullOrEmpty(pagename)) { pagename = "Default"; }

            if (context.Request.Form["op"] != null) { op = context.Request.Form["op"].ToString(); }
            if (context.Request.Form["id"] != null) { id = context.Request.Form["id"].ToString(); }
            response = "Unknown Command " + op;
            switch (op.ToLower())
            {
                case "save":
                    PageDefinition def = new PageDefinition(Web.SiteName, pagename);
                    if (!def.Found)
                    {
                        context.Response.ContentType = "text/plain";
                        context.Response.Write("Page Definition not found or created.");
                        return;
                    }
                    string html = string.Empty;
                    if (context.Request.Form["value"] != null) { html = context.Request.Form["value"]; }
                    def[id] = html;
                    def.Update(this.Username);
                    response = "OK";
                    break;
            }

            context.Response.ContentType = "text/plain";
            context.Response.Write(response);
        }
    }
}
